<!--
 * @Description:
 * @Author: Zlou
 * @Date: 2021-06-22 14:47:04
 * @LastEditors: 萧盼盼的泰迪
 * @LastEditTime: 2021-07-01 20:12:25
-->
<template>
  <!-- 添加按钮，模糊搜索，查询按钮 -->
  <div class="product-list">
    <div class="search">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <!-- 添加按钮 -->
        <el-form-item>
          <el-button size="mini" @click="toAdd" type="primary">添加</el-button>
        </el-form-item>

        <!-- 产品名称 -->
        <el-form-item>
          <el-input
            clearable
            size="mini"
            v-model="searchForm.name"
            placeholder="请输入产品名称"
          ></el-input>
        </el-form-item>
        <!-- 产品状态 -->
        <el-form-item>
          <el-select
            clearable
            size="mini"
            v-model="searchForm.status"
            placeholder="请选择产品状态"
          >
            <el-option label="正常" value="正常"></el-option>
            <el-option label="下架" value="下架"></el-option>
          </el-select>
        </el-form-item>
        <!-- 产品分类 -->
        <el-form-item>
          <el-select
            clearable
            size="mini"
            v-model="searchForm.productCategoryId"
            placeholder="请选择产品分类"
          >
            <el-option
              v-for="item in categoryData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
            <!-- <el-option label="下架" value="下架"></el-option> -->
          </el-select>
        </el-form-item>
        <!-- 查询按钮 -->
        <el-form-item>
          <el-button size="mini" type="primary" @click="toSearch"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <div>
      <el-table
        stripe
        size="mini"
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column type="index" align="center" label="序号">
        </el-table-column>
        <el-table-column prop="id" align="center" label="产品编号">
        </el-table-column>
        <el-table-column prop="name" align="center" label="名称">
        </el-table-column>
        <el-table-column align="center" label="图片">
          <template slot-scope="scope">
            <el-image
              style="width: 30px; height: 30px"
              :src="scope.row.photo"
              :preview-src-list="[scope.row.photo]"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="price" align="center" label="价格">
        </el-table-column>
        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <!-- <el-tag v-if="scope.row.status==='正常'" type="success">{{scope.row.status}}</el-tag> -->
            <el-tag
              :type="scope.row.status === '正常' ? 'success' : 'danger'"
              >{{ scope.row.status }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="category.name"
          align="center"
          label="所属栏目"
        ></el-table-column>
        <el-table-column prop="status" align="center" label="操作" width="250">
          <templat slot-scope="scope">
            <el-button
              @click="handleClick(scope.row)"
              type="text"
              size="mini"
              icon="el-icon-view"
              >查看</el-button
            >
            <el-button
              type="text"
              class="warning_info"
              size="mini"
              @click="toEdit(scope.row)"
              icon="el-icon-edit-outline"
              >编辑</el-button
            >
            <!-- <el-button @click="toOnline(scope.row.id)" type="text" size="small" v-if="scope.row.status==='下架'">上架</el-button>
                <el-button @click="toOffline(scope.row.id)" type="text" size="small" v-else>下架</el-button> -->
            <el-button
              :disabled="scope.row.status === '正常'"
              type="text"
              size="mini"
              icon="el-icon-upload2"
              @click="toOnline(scope.row.id)"
              v-if="scope.row.status === '下架'"
              >上架</el-button
            >
            <el-button
              class="red_info"
              :disabled="scope.row.status === '下架'"
              type="text"
              size="mini"
              icon="el-icon-download"
              v-else
              @click="toOffline(scope.row.id)"
              >下架</el-button
            >
          </templat>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="pagination-div">
      <el-pagination
        :current-page="params.page"
        :page-sizes="[2, 5, 10, 15, 20, 30]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 模态框 对话框-->
    <el-dialog
      title="添加产品信息"
      :visible.sync="visible"
      :before-close="toClose"
    >
      <el-form ref="ruleForm" :model="form" :rules="rules" size="small">
        <el-form-item
          prop="name"
          label="产品名称"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          prop="productCategoryId"
          label="所属栏目"
          :label-width="formLabelWidth"
        >
          <el-select v-model="form.productCategoryId" placeholder="所属栏目">
            <el-option
              v-for="item in categoryData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="price" label="价格" :label-width="formLabelWidth">
          <el-input v-model.number="form.price" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="photo" label="封面" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

        <el-form-item label="产品描述" :label-width="formLabelWidth">
          <el-input
            v-model="textarea"
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="toClose">取 消</el-button>
        <el-button type="primary" @click="toSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageQuery } from "@/api/proCategory";
// 重命名
import {
  pageQuery as pageQueryPro,
  saveOrUpdate,
  online,
  offline,
} from "@/api/product";
import { showFileURL, uploadFileURL } from "@/utils/config";

export default {
  data() {
    return {
      showFileURL,
      uploadFileURL,
      // 产品栏目的数据，页面一上来就发送请求，请求所有的产品栏目数据，设置到categoryData
      categoryData: [],
      // 模糊搜索表单的数据
      searchForm: {
        name: "",
        status: "",
        productCategoryId: "",
      },
      // 表格展示的数据
      tableData: [],
      // 分页参数
      params: {
        page: 1,
        pageSize: 10,
      },
      // 总条数
      total: 0,
      // 加载
      loading: false,
      // 模态框的显示与隐藏
      visible: false,

      // 表单数据
      form: {},
      // 表单控件标题的宽度
      formLabelWidth: "80px",
      // 模态框的标题
      title: "",
      // 图片url
      imageUrl: "",
      // 校验规则
      rules: {
        name: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
        productCategoryId: [
          { required: true, message: "请选择所属栏目", trigger: "change" },
        ],
        price: [
          { required: true, message: "请输入产品价格", trigger: "blur" },
          { type: "number", message: "请输入数值类型的价格", trigger: "blur" },
        ],
        photo: [
          { required: true, message: "请上传封面图片", trigger: "change" },
        ],
      },
    };
  },

  computed: {},
  watch: {
    // loading
    params: {
      handler() {
        this.queryData();
      },
      deep: true,
    },
  },
  created() {
    this.queryCategoryData();
    this.queryData();
  },
  mounted() {},
  methods: {
    //   获取产品分类数据
    async queryCategoryData() {
      const res = await pageQuery({ page: 1, pageSize: 100 });
      // console.log(res);
      this.categoryData = res.data.list;
    },
    // 分页模糊获取产品数据
    async queryData() {
      this.loading = true;
      // 处理数据
      const temp = {
        ...this.params,
        ...this.searchForm,
      };
      // 遍历对象
      for (const key in temp) {
        // key是一个变量，代表的属性名
        // key是属性名  temp[key]是属性值
        // console.log(key, temp[key]);
        if (!temp[key]) {
          delete temp[key];
        }
      }
      const res = await pageQueryPro(temp);
      this.tableData = res.data.list;
      this.total = res.data.total;
      // 加载完毕
      this.loading = false;
    },
    // 查询按钮点击事件处理程序
    toSearch() {
      this.queryData();
    },
    // 每页显示的条数发生变化时的事件处理程序
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      // this.params.pageSize = val;
      this.params = {
        page: 1,
        pageSize: val,
      };
    },
    // 当前页码发生变化时的时的事件处理程序
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.params.page = val;
    },
    // 添加按钮事件处理程序
    toAdd() {
      this.queryCategoryData();
      // 清空表单数据
      (this.form = {}), (this.imageUrl = ""), (this.title = "添加产品信息");
      this.visible = true;
    },
    // 图片上传成功的回调函数
    handleAvatarSuccess(res, file) {
      // console.console.log(res, "图片上传成功之后的res");
      this.imageUrl = URL.createObjectURL(file.raw);
      // console.log(this.imageUrl);
      this.form.photo = showFileURL + res.data.id;
    },
    // 图片上传之前的回调函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 模态框确认按钮事件处理程序
    toSave() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          console.log("校验通过");
          const res = await saveOrUpdate(this.form);
          // console.log(res, "-------")
          // 提示用户保存成功，刷新表格数据，关闭模态框
          this.$notify.success({
            title: "",
            message: res.message,
          });
          this.queryData();
          this.toClose();
        } else {
          return false;
        }
      });
    },
    // 关闭模态框
    toClose() {
      // 重置表单验证
      this.$refs.ruleForm.resetFields();
      //  超时调用
      setTimeout(() => {
        this.visible = false;
      }, 200);
    },
    // 编辑按钮事件处理程序
    toEdit(row) {
      this.queryCategoryData();
      // 设置表单数据
      (this.form = { ...row }),
        (this.imageUrl = this.form.photo),
        (this.title = "编辑产品信息");
      this.visible = true;
    },
    // 上架
    async toOnline(id) {
      const res = await online({ id });
      this.$notify.success({
        title: "成功！",
        message: res.message,
      });
      this.queryData();
    },
    // 下架
    async toOffline(id) {
      const res = await offline({ id });
      this.$notify.success({
        title: "成功！",
        message: res.message,
      });
      this.queryData();
    },
  },
};
</script>
<style lang="scss" scoped>
.search {
  display: flex;
  height: 50px;
}
</style>
